import * as vscode from 'vscode';
import * as fs from 'fs'; // 引入文件系统模块，用于读取 HTML 模板文件

export class HtmlBuilder {
    
    constructor(private readonly _extensionUri: vscode.Uri) {}

    public getHtml(webview: vscode.Webview): string {
    
        // ====================================================================
        // 1. 获取 CSS 资源 URI (模块化)
        // ====================================================================
        
        // 基础与布局
        const baseCssUri = this._convertVsCodeUri(webview, 'media', 'webview', 'css', 'base.css');
        const layoutCssUri = this._convertVsCodeUri(webview, 'media', 'webview', 'css', 'layout.css');
        const componentsCssUri = this._convertVsCodeUri(webview, 'media', 'webview', 'css', 'components.css');
        
        // 业务模块
        const chatCssUri = this._convertVsCodeUri(webview, 'media', 'webview', 'css', 'chat.css');
        const toolsCssUri = this._convertVsCodeUri(webview, 'media', 'webview', 'css', 'tools.css');
        const attachmentsCssUri = this._convertVsCodeUri(webview, 'media', 'webview', 'css', 'attachments.css');
        const commandCssUri = this._convertVsCodeUri(webview, 'media', 'webview', 'css', 'command.css');
        const copilotThemeCssUri = this._convertVsCodeUri(webview, 'media', 'webview', 'css', 'copilot-theme.css');

        // 第三方库
        const codiconCssUri = this._convertVsCodeUri(webview, 'node_modules', '@vscode', 'codicons', 'dist', 'codicon.css');
        
        // ====================================================================
        // 2. 获取 JS 资源 URI (MVC 架构)
        // ====================================================================

        // 第三方库 (Toolkit)
        const toolkitUri = this._convertVsCodeUri(webview, 'node_modules', '@vscode', 'webview-ui-toolkit', 'dist', 'toolkit.js');

        // 核心架构 (Core)
        const errorBoundaryUri = this._convertVsCodeUri(webview, 'media', 'webview', 'js', 'core', 'ErrorBoundary.js');
        const vsCodeAdapterUri = this._convertVsCodeUri(webview, 'media', 'webview', 'js', 'core', 'vsCodeAdapter.js');
        const appControllerUri = this._convertVsCodeUri(webview, 'media', 'webview', 'js', 'core', 'appController.js');

        // 组件 (Components)
        const dialogComponentUri = this._convertVsCodeUri(webview, 'media', 'webview', 'js', 'ui', 'components', 'DialogComponent.js');

        // 视图组件 (UI Views)
        const messageViewUri = this._convertVsCodeUri(webview, 'media', 'webview', 'js', 'ui', 'MessageView.js');
        const inputViewUri = this._convertVsCodeUri(webview, 'media', 'webview', 'js', 'ui', 'InputView.js');
        const toolResultViewUri = this._convertVsCodeUri(webview, 'media', 'webview', 'js', 'ui', 'ToolResultView.js');
        const methodSelectorUri = this._convertVsCodeUri(webview, 'media', 'webview', 'js', 'ui', 'MethodSelectorView.js');

        // 入口文件
        const mainUri = this._convertVsCodeUri(webview, 'media', 'webview', 'main.js');
        
        // ====================================================================
        // 3. 读取模板并执行替换
        // ====================================================================

        // 生成随机 nonce
        const nonce = this._getNonce(); 

        // 读取 HTML 模板
        const htmlTemplatePath = vscode.Uri.joinPath(
            this._extensionUri, 
            'media', 
            'webview', 
            'index.html'
        );
        let htmlContent = fs.readFileSync(htmlTemplatePath.fsPath, 'utf8');

       const replacements: Record<string, string> = {
            '{{cspSource}}': webview.cspSource,
            '{{nonce}}': nonce,
            
            // CSS
            '{{baseCssUri}}': baseCssUri,
            '{{layoutCssUri}}': layoutCssUri,
            '{{componentsCssUri}}': componentsCssUri,
            '{{chatCssUri}}': chatCssUri,
            '{{toolsCssUri}}': toolsCssUri,
            '{{attachmentsCssUri}}': attachmentsCssUri,
            '{{commandCssUri}}': commandCssUri,
            '{{copilotThemeCssUri}}': copilotThemeCssUri,
            '{{codiconCssUri}}': codiconCssUri,
            
            // JS
            '{{toolkitUri}}': toolkitUri,
            '{{errorBoundaryUri}}': errorBoundaryUri,
            '{{vsCodeAdapterUri}}': vsCodeAdapterUri,
            '{{appControllerUri}}': appControllerUri,
            '{{dialogComponentUri}}': dialogComponentUri,
            '{{messageViewUri}}': messageViewUri,
            '{{inputViewUri}}': inputViewUri,
            '{{toolResultViewUri}}': toolResultViewUri,
            '{{methodSelectorUri}}': methodSelectorUri,
            '{{mainUri}}': mainUri
        };

        // 批量替换
        for (const [key, value] of Object.entries(replacements)) {
            htmlContent = htmlContent.replace(new RegExp(key, 'g'), value);
        }
        
        return htmlContent;
    }

    private _convertVsCodeUri(webview: vscode.Webview, ...path: string[]): string {
        return webview.asWebviewUri(
            vscode.Uri.joinPath(this._extensionUri, ...path)
        ).toString();
    }

    /**
     * 生成随机 nonce
     * @returns 随机字符串
     */
    private _getNonce(): string {
        let text = '';
        const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        for (let i = 0; i < 32; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        return text;
    }
}
